﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using Web;

namespace DataLook.App_Start
{
	public class UpLoadFileHelper
	{
		protected readonly string FileUploadExcelTypes = ConfigurationManager.AppSettings["FileUploadExcelTypes"];
		protected readonly int UploadFileSize = int.Parse(ConfigurationManager.AppSettings["UploadExcelFileSize"]);
		protected HttpContext BaseContext = HttpContext.Current;

		/// <summary>
		/// 上传Excel
		/// </summary>
		/// <returns></returns>
		public Dictionary<int, string> UploadExcelFile()
		{
			Dictionary<int, string> hashTable = new Dictionary<int, string>();
			try
			{
				string root = DateTime.Now.ToString("yyyyMMdd");
				HttpPostedFile File = BaseContext.Request.Files[0];
				if (File == null)
				{
					hashTable.Add(0, "请选择EXCEl文件");
					return hashTable;
				}
				string uploadFileType = File.FileName.Substring(File.FileName.LastIndexOf("."));//获取文件类型
				if (!this.FileUploadExcelTypes.Contains(uploadFileType))
				{
					hashTable.Add(1, "文件类型错误");
					return hashTable;
				}
				if (this.CheckUploadFileSize(File.InputStream.Length))
				{
					hashTable.Add(2, "大小超出限制");
					return hashTable;
				}

				string strPath = "~/Uploadfile/" + root + "/";
				String rootPath = HttpContext.Current.Server.MapPath(strPath);
				//如果根目录不存在
				if (!Directory.Exists(rootPath))
				{
					//则创建
					Directory.CreateDirectory(rootPath);
				}
				String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo) + uploadFileType;
				rootPath = rootPath + newFileName;
				File.SaveAs(rootPath);
				hashTable.Add(3, rootPath);
				return hashTable;
			}
			catch (Exception ex)
			{
				LogHelper.Info("上传文件错误，错误信息：" + ex.Message);
				hashTable.Add(4, "上传文件错误");
				return hashTable;
			}
		}

		private bool CheckUploadFileSize(long fileSize)
		{
			return fileSize > this.UploadFileSize * 1024 * 1024 && fileSize > 0;
		}
	}
}